package com.jlz.actions.login;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.jlz.beans.user.LinkBean;
import com.jlz.beans.user.UserBean;
import com.jlz.managers.user.Links;
import com.jlz.managers.user.Users;
import com.julewa.Client;
import com.julewa.db.BeanValidator;

@Component
public class UserLoginChecker {

	private @Autowired Client client;
	private @Autowired Links links;
	private @Autowired Users users;
	private @Autowired BeanValidator validator;
	public enum STATE{IGNORE,ERROR,NOTICE,LOGIN,DONE}
	public STATE check(){
		if(!client.isAnonimous())return STATE.DONE;
		//
		String username = client.getParameter("j_username");
		String password = client.getParameter("j_password");
		if(StringUtils.isBlank(username) && StringUtils.isBlank(password))return STATE.IGNORE;
		
		//
		validator.checkField("j_username", "账号", username, 3, 100); 
		validator.checkField("j_password", "密码", password, 3, 64);
		if(client.hasError()) return STATE.ERROR;
		//
		UserBean user = null;
		LinkBean link = links.find(username);
		if(link != null){
			switch( Links.State.of(link.getState())){
			case NEW:{
				client.setError("j_login", "账号未激活,请从您的邮箱激活账号");
				return STATE.NOTICE;
			}
			case LOCKED: break;
			default:
				if(link.getPassword().equals(password)){
					user = users.get(link.getUserId());
				}
			}
		}
		//
		if(user == null){
			client.setError("j_login", "账号或密码错误");
			return STATE.ERROR;
		}
		client.setUser(user); 
		return STATE.LOGIN;
	}
}
